package com.yixiu.study.juc.taobao.num1;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @CalssName T01_NotifyHoldingLock
 * @Description 淘宝面试题
 * @Author yixiu
 * @Date 2021/6/25 10:23
 * @Verison num1.0
 **/
public class T01_NotifyHoldingLock {

    volatile List lists = new ArrayList();
    public void add(Object o){
        lists.add(o);
    }

    public int size(){
        return lists.size();
    }

    public static void main(String[] args) {
        T01_NotifyHoldingLock c = new T01_NotifyHoldingLock();
        final Object lock = new Object();
        //需要注意先启动线程t2再启动线程t1
        new Thread(() -> {
            synchronized (lock){
                System.out.println("t2 启动");
                if(c.size() != 5){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t2 结束");
            }
            //通知t1继续执行
            lock.notify();
        }, "t2").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            System.out.println("t1 启动");

            synchronized (lock){
                for (int i = 0; i < 10; i++) {
                    c.add(new Object());
                    System.out.println("add" + i);
                    if(c.size() == 5){
                        //通知线程t2执行
                        lock.notify();

                        try {
                            //因为 notify() 不会释放锁，所以需要调用一次 wait() 方法来释放当前持有的锁，让t2得以执行
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            System.out.println("t1 结束");
        }, "t1").start();
    }


}
